// file: echo3.js
const net = require('net');

net.createServer(socket => {
  let buf = Buffer.alloc(0);

  socket.on('data', chunk => {
    buf = Buffer.concat([buf, chunk]);

    // 简单判断：当报文里出现 \r\n\r\n 后再看 Content-Length
    const doubleCRLF = buf.indexOf('\r\n\r\n');
    if (doubleCRLF === -1) return; // 头还没收全

    const head = buf.slice(0, doubleCRLF).toString();
    const clMatch = head.match(/^content-length:\s*(\d+)/im);
    const bodyLen = clMatch ? Number(clMatch[1]) : 0;
    const bodyStart = doubleCRLF + 4;

    if (buf.length < bodyStart + bodyLen) return; // 正文没收全
    console.log( buf.toString('utf8'));
    // 构造 HTTP 响应
    const response = `HTTP/1.1 200 OK\r\n` +
                     `Content-Type: text/plain\r\n` +
                     `Content-Length: ${buf.length}\r\n` +
                     `\r\n` +
                     buf.toString('utf8'); // 将原始请求数据作为响应正文

    socket.end(response); // 发送响应并结束连接
  });
}).listen(3000, () => {
  console.log('Server listening on port 3000');
});